package demo1;

public class HashBuck2<K,V> {
    static class Node <K,V>{
        K key;
        V val;
        Node<K,V> next;
        public Node(K key,V val){
            this.key=key;
            this.val=val;
        }
    }
    public static final double Factor= 7.5;
    public Node<K,V>[] arr=(Node<K, V>[]) new Node[10];//易错点
    public int usedSize;
    public void push(K key,V val){
        int hashCode=key.hashCode();//调用hashcode()函数将其它类型转换为整型
        int index=hashCode%arr.length;
        Node<K,V> cur=arr[index];
        while(cur!=null){//更新
            if(cur.key==key){
                cur.val=val;
            }
            cur=cur.next;
        }
        //没找到就头插入
        Node<K,V> node1=new Node<>(key, val);
        node1.next=arr[index];
        arr[index]=node1;
        usedSize++;
        if(factor()>=Factor){
            resize();//扩容
        }
    }
    private int factor(){
        return usedSize/arr.length;
    }
    private void resize(){
        Node<K,V>[] arr2=new Node[2*arr.length];
        for(int i=0;i<arr.length;i++){
            Node<K,V> cur=arr[i];
            while(cur!=null){
                int  code=cur.key.hashCode()%arr2.length;
                Node<K,V> curn=arr2[code].next;//存贮下一个节点
                cur.next=arr2[code];
                arr2[code]=cur;
                cur=curn;
            }
        }
    }
    public void getval(K key){
        int code=key.hashCode();
        int index=code%arr.length;
        Node<K,V> cur=arr[index];
        while(cur!=null){
            if(cur.key==key){
                System.out.println("找到了key："+key+"对应值为："+ cur.val);
                return;
            }
            cur=cur.next;
        }
        System.out.println("没找到！");
    }
    public void display(){
        for(int i=0;i< arr.length;i++){
            Node<K,V> cur=arr[i];
            while(cur!=null){
                System.out.println("key值："+cur.key+"    val值："+cur.val);
                cur=cur.next;
            }
        }
    }


}
